package com.home.duy.code.Abstract;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.Query;

import com.home.System.*;
import com.home.duy.code.Exception.DataAccessLayerException;

public abstract class AbstractDAO {
	
	public AbstractDAO()
	{
	}
	
	protected boolean saveOrUpdate(Object obj)
	{
		boolean res = true;
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction trans = null;
		try {
			trans = session.beginTransaction();
			session.saveOrUpdate(obj);
			trans.commit();
		} catch (HibernateException he) {
			trans.rollback();
			res = false;
		}
		finally
		{
			session.close();
		}
		return res;
	}
	
	protected boolean delete(Object obj)
	{
		boolean res = true;
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction trans = null;
		try {
			trans = session.beginTransaction();
			session.delete(obj);
			trans.commit();
		} catch (HibernateException he) {
			trans.rollback();
			res = false;
		}
		finally
		{
			session.close();
		}
		return res;
	}
	
	protected Object findByPk(Class clas,long pk)
	{
		Object obj = null;
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction trans = null;
		try {
			trans = session.beginTransaction();
			obj = session.load(clas, pk);
			trans.commit();
		} catch (HibernateException he) {
			trans.rollback();
		}
		finally
		{
			session.close();
		}
		return obj;
	}
	
	protected List findAll(Class clas)
	{
		List list = null;
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction trans = null;
		try {
			trans = session.beginTransaction();
			list = session.createQuery("FROM "+clas.getName()).list();
			trans.commit();
		} catch (HibernateException he) {
			trans.rollback();
		}
		finally
		{
			session.close();
		}
		return list;
	}
}
